import { useMemo, useCallback, useRef, useEffect } from 'react';
import { RoomType, RoomStatus } from '../../../types/room';
import type { Room, RoomAvailability } from '../../../types/room';
import { dataIndexManager } from '../utils/DataIndexManager';

interface UseOptimizedRoomDataReturn {
  // 基础数据
  filteredRooms: Room[];

  // 快速查找函数
  getRoomAvailability: (
    roomId: string,
    month: string
  ) => RoomAvailability | undefined;
  getRoomAvailabilities: (roomId: string) => RoomAvailability[];

  // 高级查询函数
  getRoomsByStatus: (status: RoomStatus) => Room[];
  getRoomsByBuilding: (building: string) => Room[];
  getRoomsByTypeAndStatus: (roomType: RoomType, status: RoomStatus) => Room[];
  getAvailabilitiesInRange: (
    startMonth: string,
    endMonth: string
  ) => RoomAvailability[];

  // 统计信息
  getStatistics: () => any;
  getIndexStats: () => any;

  // 性能监控
  performanceMetrics: {
    indexBuildTime: number;
    lastQueryTime: number;
    cacheHitRate: number;
  };
}

// 性能计时器
class PerformanceTimer {
  private startTime: number = 0;

  start(): void {
    this.startTime = performance.now();
  }

  end(): number {
    return performance.now() - this.startTime;
  }
}

export const useOptimizedRoomData = (
  rooms: Room[],
  availabilities: RoomAvailability[],
  selectedRoomType: RoomType
): UseOptimizedRoomDataReturn => {
  const performanceTimer = useRef(new PerformanceTimer());
  const metricsRef = useRef({
    indexBuildTime: 0,
    lastQueryTime: 0,
    cacheHitRate: 0,
  });

  // 构建索引 (使用 useMemo 优化)
  const indexReady = useMemo(() => {
    performanceTimer.current.start();

    // 构建多维索引
    dataIndexManager.buildIndex(rooms, availabilities);

    const buildTime = performanceTimer.current.end();
    metricsRef.current.indexBuildTime = buildTime;

    console.log(`数据索引构建完成，耗时: ${buildTime.toFixed(2)}ms`);

    return true;
  }, [rooms, availabilities]);

  // 根据房型筛选房间 (使用索引优化)
  const filteredRooms = useMemo(() => {
    if (!indexReady) return [];

    performanceTimer.current.start();

    let result: Room[];
    if (selectedRoomType === RoomType.ALL) {
      // 获取所有房间，并按房型分组排序
      result = [...rooms].sort((a, b) => {
        // 定义房型优先级
        const typeOrder: Record<string, number> = {
          [RoomType.STANDARD_SINGLE]: 1,
          [RoomType.DELUXE_KING]: 2,
          [RoomType.EXECUTIVE_SUITE]: 3,
        };

        const aOrder = typeOrder[a.roomType] || 999;
        const bOrder = typeOrder[b.roomType] || 999;

        if (aOrder !== bOrder) {
          return aOrder - bOrder; // 先按房型排序
        }

        // 同房型内按房间号排序
        return a.roomNumber.localeCompare(b.roomNumber);
      });
    } else {
      // 使用索引快速查找
      result = dataIndexManager.getRoomsByType(selectedRoomType);
    }

    const queryTime = performanceTimer.current.end();
    metricsRef.current.lastQueryTime = queryTime;

    console.log(
      `房型筛选查询完成，耗时: ${queryTime.toFixed(2)}ms，结果: ${result.length}个房间`
    );

    return result;
  }, [rooms, selectedRoomType, indexReady]);

  // 快速查找房间可用性 O(1)
  const getRoomAvailability = useCallback((roomId: string, month: string) => {
    performanceTimer.current.start();
    const result = dataIndexManager.getRoomAvailability(roomId, month);
    const queryTime = performanceTimer.current.end();
    metricsRef.current.lastQueryTime = queryTime;
    return result;
  }, []);

  // 批量查找房间可用性
  const getRoomAvailabilities = useCallback((roomId: string) => {
    performanceTimer.current.start();
    const result = dataIndexManager.getRoomAvailabilities(roomId);
    const queryTime = performanceTimer.current.end();
    metricsRef.current.lastQueryTime = queryTime;
    return result;
  }, []);

  // 按状态查找房间
  const getRoomsByStatus = useCallback((status: RoomStatus) => {
    performanceTimer.current.start();
    const result = dataIndexManager.getRoomsByStatus(status);
    const queryTime = performanceTimer.current.end();
    metricsRef.current.lastQueryTime = queryTime;
    console.log(
      `状态查询 ${status}: ${result.length}个房间，耗时: ${queryTime.toFixed(2)}ms`
    );
    return result;
  }, []);

  // 按建筑查找房间
  const getRoomsByBuilding = useCallback((building: string) => {
    performanceTimer.current.start();
    const result = dataIndexManager.getRoomsByBuilding(building);
    const queryTime = performanceTimer.current.end();
    metricsRef.current.lastQueryTime = queryTime;
    console.log(
      `建筑查询 ${building}: ${result.length}个房间，耗时: ${queryTime.toFixed(2)}ms`
    );
    return result;
  }, []);

  // 复合查询：按房型和状态查找
  const getRoomsByTypeAndStatus = useCallback(
    (roomType: RoomType, status: RoomStatus) => {
      performanceTimer.current.start();
      const result = dataIndexManager.getRoomsByTypeAndStatus(roomType, status);
      const queryTime = performanceTimer.current.end();
      metricsRef.current.lastQueryTime = queryTime;
      console.log(
        `复合查询 ${roomType}+${status}: ${result.length}个房间，耗时: ${queryTime.toFixed(2)}ms`
      );
      return result;
    },
    []
  );

  // 范围查询
  const getAvailabilitiesInRange = useCallback(
    (startMonth: string, endMonth: string) => {
      performanceTimer.current.start();
      const result = dataIndexManager.getAvailabilitiesInRange(
        startMonth,
        endMonth
      );
      const queryTime = performanceTimer.current.end();
      metricsRef.current.lastQueryTime = queryTime;
      console.log(
        `范围查询 ${startMonth}-${endMonth}: ${result.length}条记录，耗时: ${queryTime.toFixed(2)}ms`
      );
      return result;
    },
    []
  );

  // 获取统计信息
  const getStatistics = useCallback(() => {
    performanceTimer.current.start();
    const result = dataIndexManager.getStatistics();
    const queryTime = performanceTimer.current.end();
    metricsRef.current.lastQueryTime = queryTime;
    return result;
  }, []);

  // 获取索引统计
  const getIndexStats = useCallback(() => {
    const stats = dataIndexManager.getStats();
    const cacheHitRate =
      stats.hitCount / (stats.hitCount + stats.missCount) || 0;
    metricsRef.current.cacheHitRate = cacheHitRate;
    return stats;
  }, []);

  // 监控性能指标
  useEffect(() => {
    const interval = setInterval(() => {
      const stats = getIndexStats();
      console.log('数据索引性能统计:', {
        索引构建时间: `${metricsRef.current.indexBuildTime.toFixed(2)}ms`,
        最近查询时间: `${metricsRef.current.lastQueryTime.toFixed(2)}ms`,
        缓存命中率: `${(metricsRef.current.cacheHitRate * 100).toFixed(1)}%`,
        索引大小: stats.indexSize,
      });
    }, 10000); // 每10秒输出一次统计信息

    return () => clearInterval(interval);
  }, [getIndexStats]);

  return {
    filteredRooms,
    getRoomAvailability,
    getRoomAvailabilities,
    getRoomsByStatus,
    getRoomsByBuilding,
    getRoomsByTypeAndStatus,
    getAvailabilitiesInRange,
    getStatistics,
    getIndexStats,
    performanceMetrics: metricsRef.current,
  };
};
